"""
$ sanic main:app --reload
"""
from sqlalchemy import INTEGER, Column, String, select
from sqlalchemy.orm import declarative_base

Base = declarative_base()


class BaseModel(Base):
    __abstract__ = True
    id = Column(INTEGER(), primary_key=True)


class Staffs(BaseModel):
    __tablename__ = "staffs"
    name = Column(String(length=20))
    age = Column(INTEGER())
    pos = Column(String(length=20))

    def to_dict(self):
        return {"name": self.name, "cars": [{"brand": car.brand} for car in self.cars]}



from sanic import Sanic, json
from sqlalchemy.ext.asyncio import create_async_engine
from contextvars import ContextVar
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import sessionmaker

app = Sanic("my_app")
url = 'postgresql+asyncpg://postgres:postgres@172.17.0.2:5432/test'
url2 = 'mysql+aiomysql://root:123456@localhost/test'
bind = create_async_engine(url, echo=True)

_base_model_session_ctx = ContextVar("session")


@app.middleware("request")
async def inject_session(request):
    request.ctx.session: AsyncSession = sessionmaker(bind, AsyncSession, expire_on_commit=False)()
    # request.ctx.session.run_sync()
    request.ctx.session_ctx_token = _base_model_session_ctx.set(request.ctx.session)


@app.middleware("response")
async def close_session(request, response):
    if hasattr(request.ctx, "session_ctx_token"):
        _base_model_session_ctx.reset(request.ctx.session_ctx_token)
        await request.ctx.session.close()


@app.route('/api/v1/data', methods=['GET'])
async def data(request):
    session: AsyncSession = request.ctx.session
    async with session.begin():
        stmt = select(Staffs)
        row = await session.execute(stmt)
        row = row.scalars()
        for i in row:
            print(i.name)

    return json({})

